package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.Delete;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;
    
    /**
     * 关注和取关
     * @param followUserId 粉丝用户ID
     * @param isFollow 布尔类型 表示关注或取关
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //1.获取当前用户
        final Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId; //前缀
        //2.判断到底是关注还是取关
        if (isFollow){
            //2.1 若关注，则向数据库写入数据
            final Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            final boolean isSuccess = save(follow);
            if (isSuccess){
                redisTemplate.opsForSet().add(key, followUserId.toString());//向redis添加set集合数据
            }
        }else {
            //2.2 若取关，则将删除数据库数据
            final boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId)
                    .eq("follow_user_id", followUserId));
            if (isSuccess){
                redisTemplate.opsForSet().remove(key, followUserId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 判断是否关注
     * @param followUserId 粉丝用户ID
     * @return 返回布尔类型
     */
    @Override
    public Result isFollow(Long followUserId) {
        //当前用户ID
        final Long userId = UserHolder.getUser().getId();
        final Long count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();

        return Result.ok(count > 0);
    }

    /**
     * 获取共同关注好友列表
      * @param id 博主的ID
     * @return
     */
    @Override
    public Result followCommons(Long id) {
        final Long userId = UserHolder.getUser().getId();
        String key1 = "follows:" + userId;
        String key2 = "follows:" + id;
        final Set<String> intersect = redisTemplate.opsForSet().intersect(key1, key2);
        if (intersect == null || intersect.isEmpty()){
            //无交集，也就是说无共同关注的好友
            return Result.ok(Collections.emptyList());
        }
        //解析ID集合（String->Long，Set->List）
        final List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());//存放着交集的用户ID

        //根据ID查询用户
        final List<User> userList = userService.listByIds(ids);

        final List<UserDTO> userDTOList = userList
                .stream()
                .map(User -> BeanUtil.copyProperties(User, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOList);
    }
}
